package com.example.spring_java_oj.service;

import com.example.spring_java_oj.Util.FileUtil;
import com.example.spring_java_oj.model.*;
import com.example.spring_java_oj.service.userInfo.UserInfoRedisService;
import com.example.spring_java_oj.service.userInfo.UserInfoService;
import com.fasterxml.jackson.core.JsonProcessingException;
import lombok.val;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@Service
public class UserInfoAmountService {

    @Autowired
    private UserInfoService userInfoService;

    @Autowired
    private UserInfoRedisService userInfoRedisService;

    public UserInfo queryByName(String userName) throws JsonProcessingException {
        UserInfo userInfo = userInfoRedisService.queryByName(userName);
        if (userInfo == null){
            userInfo = userInfoService.queryByName(userName);
            if(userInfo != null){
                userInfoRedisService.register(userInfo);
            }
        }
        return userInfo;
    }

    public UserInfo queryById(Integer userId) throws JsonProcessingException {
        UserInfo userInfo = userInfoRedisService.queryById(userId);
        if (userInfo == null){
            userInfo = userInfoService.queryById(userId);
            if(userInfo != null){
                userInfoRedisService.register(userInfo);
            }
        }
        return userInfo;
    }


    public CompileResponse run(Integer id, String code, HttpServletRequest request) {
        CompileResponse response = userInfoService.run(id, code, request);
        return response;
    }

    public boolean register(String username, String passwordA, String passwordB) throws JsonProcessingException {
        boolean b = userInfoService.regster(username, passwordA, passwordB);
        if (b){
            UserInfo userInfo = userInfoService.queryByName(username);
            userInfoRedisService.register(userInfo);
        }
        return b;
    }

}
